from concurrent import futures
import grpc
from protos import greater_pb2_grpc
from app.rpc.greeter_rpc_service import GreeterRcpServic

import logging
from demo.common.logging.logging_config import setup_logging
setup_logging()
logger = logging.getLogger(__name__)

from database import ScopedSession
class ScopedSessionInterceptor(grpc.ServerInterceptor):
    def intercept_service(self, continuation, handler_call_details):
        session = ScopedSession()
        logger.info(f"create session {session}")
        response = continuation(handler_call_details)
        try:
            return response
        finally:
            logger.info(f"remove session {session}")
            ScopedSession.remove()

from grpc_interceptor import ServerInterceptor
class ScopedSessionInterceptor2(ServerInterceptor):
    def intercept(self, method, request, context, method_name):
        session = ScopedSession()
        logger.info(f"create session {method_name} {session}")
        try:
            return method(request, context)
        finally:
            logger.info(f"remove session {method_name} {session}")
            ScopedSession.remove()

def serve():
    # 创建一个服务器
    server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=10),
        interceptors=[ScopedSessionInterceptor2()]
    )
    # 将定义的服务添加到服务器中
    greater_pb2_grpc.add_GreeterServicer_to_server(GreeterRcpServic(), server)
    # 指定监听的端口
    server.add_insecure_port('[::]:50051')
    # 启动服务器
    server.start()
    # 服务器无限期运行
    server.wait_for_termination()

if __name__ == '__main__':
    print('Starting server. Listening on port 50051.')
    serve()
